#!/bin/sh

APP_MAINCLASS=com.tcm.luck.main.TcmLuckApiApplication
APP_MAIN_JAR=tcm-luck-api-0.0.1-SNAPSHOT.jar

#java options
#ms inin memery
#mx max memery
#mn young memery
JAVA_OPTS="-server -XX:-PrintGC -XX:-PrintGCDetails -XX:-PrintGCTimeStamps -Xloggc:logs/gc.log"

APP_HOME=.
for i in "$APP_HOME"/lib/*.jar; do
   CLASSPATH="$CLASSPATH":"$i"
done
CLASSPATH="$CLASSPATH":"$APP_MAIN_JAR"

#echo $CLASSPATH

psid=0
checkpid() {
   javaps=`$JAVA_HOME/bin/jps -l | grep $APP_MAINCLASS`
   if [ -n "$javaps" ]; then
      psid=`echo $javaps | awk '{print $1}'`
   else
      psid=0
   fi
}

start() {
   checkpid

   if [ $psid -ne 0 ]; then
      echo "================================"
      echo "warn: $APP_MAINCLASS already started! (pid=$psid)"
      echo "================================"
   else
      echo -n "Starting $APP_MAINCLASS ..."
      nohup java -server $JAVA_OPTS -classpath $CLASSPATH $APP_MAINCLASS /dev/null 2>&1 & 
      #JAVA_CMD="nohup java -server $JAVA_OPTS -classpath $CLASSPATH $APP_MAINCLASS /dev/null 2>&1 &"
     # su - $RUNNING_USER -c "$JAVA_CMD"
      checkpid
      if [ $psid -ne 0 ]; then
         echo "(pid=$psid) [OK]"
      else
         echo "[Failed]"
      fi
   fi
}

stop() {
   checkpid
   if [ $psid -ne 0 ]; then
      echo -n "Stopping $APP_MAINCLASS ...(pid=$psid) "
#      su - $RUNNING_USER -c "kill -15 $psid"
      kill -15 $psid
      if [ $? -eq 0 ]; then
         echo "[OK]"
      else
         echo "[Failed]"
      fi
      checkpid
      if [ $psid -ne 0 ]; then
         stop
      fi
   else
      echo "================================"
      echo "warn: $APP_MAINCLASS is not running"
      echo "================================"
   fi
}

status() {
   checkpid
   if [ $psid -ne 0 ];  then
      echo "$APP_MAINCLASS is running! (pid=$psid)"
   else
      echo "$APP_MAINCLASS is not running"
   fi
}

info() {
   echo "System Information:"
   echo "****************************"
   echo `head -n 1 /etc/issue`
   echo `uname -a`
   echo
   echo "JAVA_HOME=$JAVA_HOME"
   echo `$JAVA_HOME/bin/java -version`
   echo
   echo "APP_HOME=$APP_HOME"
   echo "APP_MAINCLASS=$APP_MAINCLASS"
   echo "****************************"
}

if [ ! -n "$1" ] ;then
 echo "Usage: $0 {start|stop|status|info}"
elif [ $1 = "start" ];then
 start
elif [ $1 = "stop" ];then
 stop
elif [ $1 = "status" ];then
 status
elif [ $1 = "info" ];then
 info
fi
